<template>
<div class="addUser">
  <el-row>
    <el-col :span="12">
      <el-form ref="userForm" :model="userForm" :rules="rules" label-width="80px" class="userForm">
        <el-col :span="18">
          <el-form-item label="个人头像">
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
            <img v-else :src="env.baseUrl + '/sys/member/avatar/m/0'" class="avatar">
            <el-upload
              class="avatar-uploader"
              :action="env.baseUrl + '/file/upload'"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :headers="headers">
              <span slot="trigger" class="upload">上传头像</span>
              <span class="tips">（格式：JPG、JPEG、PNG大小不超过3M）</span>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" placeholder="英文或者英文+数字" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userForm.password" placeholder="8位及以上数字+字母组合" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realname">
            <el-input v-model="userForm.realname"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="userForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="所属架构" prop="groupId">
            <el-select placeholder="请选择" v-model="userForm.groupId">
              <el-option v-for="item in groups" :key="item.groupId" :label="item.groupName" :value="item.groupId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="characterId">
            <el-select placeholder="请选择" v-model="userForm.characterId">
              <el-option v-for="item in roles" :key="item.gid" :label="item.cName" :value="item.cid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限" prop="authority">
            <el-button :disabled="!userForm.characterId" @click="handleSetAuth" :title="userForm.characterId?'':'请选择角色'">赋予权限</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-col>
    <el-col :span="12">
      <div class="uploadUsers">
        <h2>批量导入用户 <a :href="env.baseUrl + '/sys/member/excel/template'" class="dlModel" download>下载导入模板</a></h2>
        <el-upload
          ref="upload"
          :action="env.baseUrl + '/sys/member/excel/import'"
          :headers="headers"
          :file-list="fileList"
          :auto-upload="false"
          :before-upload="beforeImportUpload"
          :on-success="handleImportSuccess">
          <el-input slot="trigger" readonly>
            <el-button slot="append">浏览</el-button>
          </el-input>
          <el-button @click="$refs.upload.submit()">上传</el-button>
          <div slot="tip" class="el-upload__tip">格式xls，xlsx，大小不超过3M</div>
        </el-upload>  
      </div>
      <div v-if="importUser.done" class="upload_result">
        <h2>导入结果</h2>
        <div class="result">
          <p>成功：<i class="red">{{importUser.success}}</i>条</p>
          <p>失败：<i class="red">{{importUser.fail}}</i>条</p>
          <a v-if="importUser.fail" :href="env.baseUrl + '/sys/member/excel/error-list?key=' + importUser.errorList" download>下载导入失败列表</a>
        </div>
      </div>
    </el-col>
  </el-row>
  <div class="split"></div>
  <el-row class="bottom">
    <el-col :span="24">
      <el-button type="primary" style="width:100px" @click="submitForm('userForm')">保存</el-button>
    </el-col>
  </el-row>
  <!-- 权限弹层 -->
  <el-dialog title="权限设置" :visible.sync="dialogVisible" custom-class="auth-dialog" @open="handleOpenDialog">
    <auth-list ref="AList" :auths="authData" :roleAuth="userForm.authority"></auth-list>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSaveAuth">保存</el-button>
    </div>
  </el-dialog>
</div>
</template>
<script>
  import {mapState, mapActions} from 'vuex'
  import authList from '@/components/common/sysManage/authList'
  import env from '@/config/env'
  export default {
    data () {
      return {
        userForm: {
          avatar: '',
          username: '',
          password: '',
          realname: '',
          email: '',
          phone: '',
          groupId: '',
          characterId: '',
          authority: ''
        },
        rules: {
          username: [{required: true, message: '请输入用户名', trigger: 'blur'},
                     {pattern: /^[a-zA-Z][a-zA-Z0-9]{4,19}$/, message: '用户名长度为5-20位字符，以英文字母开头', trigger: 'blur'}],
          password: [{required: true, message: '请输入密码', trigger: 'blur'},
                     {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/, message: '密码不符合规则', trigger: 'blur'}],
          realname: {required: true, message: '请输入真实姓名', trigger: 'blur'},
          email: [{required: true, message: '请输入邮箱', trigger: 'blur'},
                  {pattern: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, message: '邮箱不合法', trigger: 'blur'}],
          phone: [{required: true, message: '请输入手机号码', trigger: 'blur'},
                  {pattern: /^[1][0-9]{10}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
          groupId: {required: true, message: '请选择所属架构'},
          characterId: {required: true, message: '请选择所属角色'}
        },
        fileList: [],
        importUser: {
          done: false,
          fail: 0,
          success: 0,
          errorList: null
        },
        dialogVisible: false
      }
    },
    mounted () {
      this.getAuthList()
      this.getGroupMenu()
      this.getRoleList2()
    },
    components: {
      authList
    },
    computed: {
      ...mapState({
        authData: state => state.sysManage.authList,
        groups: state => state.groupMenu,
        roles: state => state.sysManage.roles
      }),
      // 文件上传附加的头部
      headers () {
        return {
          UBToken: localStorage.getItem('UBToken')
        }
      },
      env () {
        return env
      }
    },
    methods: {
      ...mapActions(['getGroupMenu', 'getRoleList2', 'getAuthList', 'addUser']),
      // 保存选中的权限
      handleSaveAuth () {
        this.userForm.authority = this.$refs.AList.checkedList.join(',')
        this.dialogVisible = false
        this.$refs.userForm.validateField('authority')
      },
      handleSetAuth () {
        if (this.$refs.AList) {
          this.$refs.AList.checkedList = this.userForm.authority.split(',').map(x => +x)
        }
        this.dialogVisible = true
      },
      // 头像上传成功
      handleAvatarSuccess (res, file) {
        this.userForm.avatar = res.data
      },
      // 头像上传检验
      beforeAvatarUpload (file) {
        const allowTypes = ['image/jpg', 'image/jpeg', 'image/png']
        const isLt2M = file.size / 1024 / 1024 < 3
        if (allowTypes.indexOf(file.type) === -1) {
          this.$message.warning('上传头像图片只能是 JPG/PNG/JPEG 格式!')
          return false
        }
        if (!isLt2M) {
          this.$message.warning('上传头像图片大小不能超过 3MB!')
          return false
        }
      },
      // 保存新建用户
      submitForm (form) {
        if (this.userForm.avatar === env.baseUrl + '/sys/member/avatar/m/0') {
          this.userForm.avatar = null
        }
        this.$refs[form].validate(valid => {
          if (valid) {
            this.addUser(this.userForm)
              .then(res => {
                if (res.data.code === 1) {
                  this.$router.push({name: 'User'})
                }
              })
          }
        })
      },
      // 导入成功
      handleImportSuccess (res) {
        this.importUser.done = true
        this.importUser = {...this.importUser, ...res.data}
      },
      // 批量导入检验
      beforeImportUpload (file) {
        const isLt3M = file.size / 1024 / 1024 < 3
        if (!file.name.match(/.xlsx$|.xls/)) {
          this.$message.warning('只能是 xls, xlsx 格式!')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!isLt3M) {
          this.$message.warning('导入文件大小不能超过 3MB!')
          return false
        }
      },
      // 打开权限弹层
      handleOpenDialog () {
        if (this.$refs.AList) {
          this.$refs.AList.init()
        }
      }
    }
  }
</script>
<style lang="scss">
  .addUser{
    position:relative;
    padding-bottom:77px;
    .userForm{
      .avatar{display:block;width:90px;height:90px;border-radius:50%;border:1px solid #c2cdda}
      .upload{margin-left:15px;color:#23a2ff}
      .tips{color:#8492a6}
      .el-input__inner{max-width: 500px}
    }
    .auth-dialog{width:640px;}
    .auth-dialog .authList{height:618px;overflow-y: scroll}
    .split{position:absolute;top:0;left:50%;width:1px;height:100%;background:#e0e6ed}
    .bottom{position:absolute;bottom:0;left:0;width:100%;padding:20px 0;background:#fff;text-align:center;border-top:1px solid #e0e6ed;} 
    .uploadUsers{
      width: 70%;
      padding-left:50px;
      .el-upload{width:calc(100% - 75px);position: relative;top: -11px;}
      h2{margin-bottom:15px;color:#475669}
      .dlModel{float:right;font-size:12px;color:#a5b4c7;font-weight:500;text-decoration:none;}
      .dlModel:hover{color:#23a2ff}
    }
    .upload_result{
      &{margin-top:20px;margin-left:50px;padding-top:10px;border-top:1px solid #eee;}
      .result{margin-top:10px;font-size:14px;}
      a{display:block;margin-top:10px;color:#a5b4c7;text-decoration:none;}
      a:hover{color:#23a2ff}
    }
  }
</style>
